<?php


namespace App\Admin\Controllers;


use App\Http\Controllers\Controller;
use App\Models\AdminUser;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ApiController extends Controller
{
    public function searchUser(Request $request, $type = null)
    {
        $q = $request->get('q');
        return AdminUser::query()
            ->where('id', '>', 1)
            ->where(function (Builder $query) use ($q) {
                $query->where('name', 'like', "%$q%")
                    ->orWhere('username', 'like', "$q%");
            })
            ->paginate(null, ['id',
                $type === 'concat' ? DB::raw("concat(username,'-',name) as text") : 'name as text'
            ]);
    }

    public function participant(Request $request)
    {
        $id = $request->get('id');
        $column = $request->get('column');
        if (!$id || !$column) {
            return response('', 404);
        }
        $model = AdminUser::query()
            ->select(['id', 'username', 'name', 'department_id', 'academic_title'])
            ->where('id', '>', 1)->findOrFail($id);
        $vo = [
            'name'          => $model['name'],
            'dw'            => $model->department->name ?? '',
            'zc'            => $model['academic_title'],
            'user_id'       => $model['id'],
            'department_id' => $model['department_id']
        ];
        $content = view('admin.participants.template', compact('column', 'vo'))->render();
        return response($content);
    }

}
